package com.zpy.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zpy.pojo.Book;
import com.zpy.pojo.Borrow;
import com.zpy.pojo.Circulate;
import com.zpy.pojo.User;
import com.zpy.service.BookService;
import com.zpy.service.BorrowService;
import com.zpy.service.UserRoleService;
import com.zpy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
@RequestMapping("reader")
public class ReaderController {
    @Autowired
    private UserService userService;

    @Autowired
    private BookService bookService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private BorrowService borrowService;
    //注册用户
    @RequestMapping("register")
    public String register(User user, Model model){
        QueryWrapper<User>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",user.getUsername());
        User user1 = userService.getOne(queryWrapper);
        if (user1!=null){
            model.addAttribute("msg","此用户已存在");
            return "register";
        }
        //手机号校验
        String regex = "^1[3456789]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(user.getPhone());
        boolean matches = matcher.matches();
        if (!matches){
            model.addAttribute("msg","手机格式错误");
            return "register";
        }
        //邮箱验证
        String regex1 = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        Pattern pattern1 = Pattern.compile(regex1);
        Matcher matcher1 = pattern1.matcher(user.getEmail());
        boolean matches1 = matcher1.matches();
        if (!matches1){
            model.addAttribute("msg","邮箱格式错误");
            return "register";
        }
        boolean save = userService.save(user);

        //添加用户-角色表
        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.eq("username",user.getUsername());
        User one = userService.getOne(qw);
        boolean b=userRoleService.saveReaderRole(one.getId());
        return "index";


    }


    //查看图书详情
    @RequestMapping("listBook")
    public String listBook(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize, Model model, HttpSession session,Book book){
        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book> qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());
        }
        qw.orderByAsc("status");
        qw.eq("isopen",1);//查看所有公开的图书
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "reader-book-list";
    }

    //详情
    @RequestMapping("detail/{id}")
    public String detail(@PathVariable Integer id, Model model){
        Book byId = bookService.getById(id);
        model.addAttribute("book",byId);
        return "reader-book-detail";
    }


    //借阅图书的列表
    @RequestMapping("listBorrow")
    public String listBook(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                           @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize, Model model, Book book){

        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Book> qw=new QueryWrapper<>();
        if (book.getBname()!=null){
            qw.like("bname",book.getBname());
        }
        qw.orderByAsc("status");
        qw.eq("isopen",1);//公开的
        qw.eq("status",0);//状态是可借阅的
        List<Book> list = bookService.list(qw);
        PageInfo<Book> pageInfo = new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "reader-book-borrow";

    }

    //跳转到申请借阅的页面
    @RequestMapping("saveBorrowBook/{bookId}")
    public String saveBorrowBook(@PathVariable Integer bookId,Model model,HttpSession session){
        Book byId = bookService.getById(bookId);
        model.addAttribute("book",byId);
        Integer userId = (Integer) session.getAttribute("userId");
        String username = (String) session.getAttribute("currentUser");
        String unit = (String) session.getAttribute("unit");
        model.addAttribute("username",username);
        model.addAttribute("userId",userId);
        model.addAttribute("unit",unit);
        Circulate circulate=new Circulate();
        return "reader-borrow-save";
    }

    //添加借阅申请
    @RequestMapping("saveBorrow")
    public String saveCirculate(Borrow borrow){
        Book book = bookService.getById(borrow.getBid());
        book.setStatus(2);//申请中
        bookService.updateById(book);
        boolean save = borrowService.save(borrow);
        return "redirect:/reader/listMyBorrow";
    }

    //我的借阅
    @RequestMapping("listMyBorrow")
    public String listMyBorrow(@RequestParam(required = false,value ="pageNum",defaultValue = "1")Integer pageNum,
                               @RequestParam(required = false,value ="pageSize",defaultValue = "10")Integer pageSize,
                               HttpSession session,Model model, Borrow borrow){
        if (pageNum<0 || pageNum.equals("") || pageNum==null){
            pageNum=1;
        }
        if (pageSize<0 || pageSize.equals("") || pageSize==null){
            pageSize=10;
        }
        PageHelper.startPage(pageNum,pageSize);
        QueryWrapper<Borrow>qw=new QueryWrapper<>();
        if (borrow.getBid()!=null){
            qw.eq("bid",borrow.getBid());
        }
        Integer userId = (Integer) session.getAttribute("userId");
        qw.eq("uid",userId);
        List<Borrow> list = borrowService.list(qw);
        for (Borrow borrow1 : list) {
            Book book = bookService.getById(borrow1.getBid());
            borrow1.setBname(book.getBname());
            borrow1.setAuthor(book.getAuthor());
            borrow1.setPage(book.getPage());
            borrow1.setPrice(book.getPrice());
            borrow1.setPress(book.getPress());
            borrow1.setType(book.getType());
        }
        PageInfo<Borrow>pageInfo=new PageInfo<>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "reader-myBorrow";
    }

    //归还图书
    @RequestMapping("returnBook/{id}")
    public String returnBook(@PathVariable Integer id){
        Borrow borrow = borrowService.getById(id);
        //修改借阅状态为3 表示归还中
        borrow.setStatus(3);
        boolean b = borrowService.updateById(borrow);
        return "redirect:/reader/listMyBorrow";
    }
}
